/*
 * @Author: your name
 * @Date: 2020-09-01 10:59:27
 * @LastEditTime: 2020-09-14 15:20:35
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \admin-management\web\src\utils\axios.js
 */
import axios from 'axios';
import qs from 'qs';
import { ElMessage,ElLoading } from 'element-plus'

import store from '../store/index';
import router from '../router/index';

import { BASE_URL } from './config';

let loadingCount: number = 0;
let  errorMsg: any = null;
//设置axios为form-data
// axios.defaults.headers.post['content-type'] = 'charset=UTF-8 application/x-www-form-urlencoded';
const service = axios.create({

  // baseURL: BASE_URL + '/admin_api.php',
  headers: { 'content-type': 'application/x-www-form-urlencoded' },
  baseURL: '/api',
  timeout: 10000
});

service.interceptors.request.use(
  (config) => {
    store.dispatch('CHANGE_LOAD', true);
    loadingCount++;
    if (store.state.token) {
      config.headers.Authorization = store.state.token;
    }
    return config;
  },
  (error) => {
    loadingCount--;
    if (loadingCount <= 0) {
      loadingCount = 0;
      store.dispatch('CHANGE_LOAD', false);
    }
    return Promise.reject(error);
  }
);

service.interceptors.response.use(
  (response: any) => {
    loadingCount--;
    if (loadingCount <= 0) {
      loadingCount = 0;
      store.dispatch('CHANGE_LOAD', false);
    }
    if (response.status === 401 && response.data.Code === 400) {
      if (errorMsg) {
        return;
      }
      errorMsg = ElMessage.error(response.data.Msg);
      setTimeout(() => {
        errorMsg = null;
      }, 1000);
      router.replace({
        name: 'Login'
      });
      store.commit('CLEAR_CACHE');
      return;
    }
    return response;
  },
  (error: any) => {
    store.dispatch('CHANGE_LOAD', false);
    if (error.response.status === 401 && error.response.data.Code === 400) {
      errorMsg = ElMessage.error(error.response.data.Msg);
      setTimeout(() => {
        errorMsg = null;
      }, 1000);
      router.replace({
        name: 'Login'
      });
    }
    loadingCount = 0;
    console.dir(error);
    if (!error.response) {
      ElMessage.error(error.message);
    }
    return Promise.reject(error);
  }
);

export default {

  get: (url: string, params = {}, config = {}): Promise<any> => {
    return new Promise((resolve, reject) => {
      const loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      service
        .get(url, {
          params,
          ...config
        })
        .then(
          (response) => {
            if (response.data.Code < 0) {
              loading.close()
              // ElMessage.error(response.data.Msg);
              reject(response.data);
            }
            loading.close()
            resolve(response.data);
          },
          (err) => {
            loading.close()
            reject(err);
          }
        );
    });
  },
  post: (url: string, params = {}, config = {}): Promise<any> => {
    return new Promise((resolve, reject) => {
      const loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      service.post(url, qs.stringify(params), config).then(
        (response) => {
          if (response.data.Code < 0) {
            loading.close()
            // ElMessage.error(response.data.Msg);
            reject(response.data);
          }
          loading.close()
          resolve(response.data);
          return;
        },
        (err) => {
          loading.close()
          reject(err);
        }
      );
    });
  }
};
